import 'package:dio/dio.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'package:volume_controller/volume_controller.dart';
import '../api/http_head.dart';
import '../api/plan/plan.dart';
import '../models/plan/plan_study_model.dart';
import '../values/constants.dart';
import 'audio_play_manager.dart';

class BackgroundServiceManager {
  static final BackgroundServiceManager _instance =
  BackgroundServiceManager._internal();

  factory BackgroundServiceManager() => _instance;

  BackgroundServiceManager._internal();

  Future<void> initializeService() async {
    final service = FlutterBackgroundService();
    await service.configure(
      androidConfiguration: AndroidConfiguration(
        onStart: onStart,
        autoStart: true,
        isForegroundMode: true,
      ),
      iosConfiguration: IosConfiguration(),
    );
    service.on('my').listen((event) {
      print('Received data: ${event}');
    });
  }

  @pragma('vm:entry-point')
  static void onStart(ServiceInstance service) async {
    // 设置周期性任务
    final audioPlayerManager = AudioPlayerManager();
    final Dio dio = Dio();
    dio.options.connectTimeout = 20000; // 连接超时时间
    dio.options.receiveTimeout = 20000; // 接收超时时
    String minioHttp = HttpHead.minioUrl();
    Timer.periodic(Duration(seconds: 60), (timer) async {
      final prefs = await SharedPreferences.getInstance();
      print("定时器已打开");
      String? studyPlanId = prefs.getString("studyPlanId");
      String httpHead =
          "${prefs.getString(Constants.prefixIp)}://${prefs.getString(
          Constants.ip)}:${prefs.getString(Constants.port)}";
      String? playFlag = prefs.getString("playFlag");
      if (playFlag == "" || playFlag == null) {
        playFlag = "2";
      }
      try {
        // 定义自定义头部信息
        final customHeaders = {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ${prefs.getString(Constants.storageToken)}',
        };
        var aa;
        try {
          final params = {
            "id": studyPlanId == "" ? 0 : studyPlanId,
            "playFlag": playFlag
          };
          final response = await dio.get(
              httpHead + "/plStudySchedule/checkAudioPlay",
              options: Options(headers: customHeaders),
              queryParameters: params);
          aa = response.data;
        } on DioError catch (e) {
          prefs.setString("playFlag", "0");
          print("-----------" + e.message + "有问题");
          return;
        }
        if (aa["data"]['playFlag'] == "0") {
          audioPlayerManager.stop();
          audioPlayerManager.setAudioUrls([]);
          prefs.setString("playFlag", "0");
        }
        if (aa["data"]['playFlag'] == "1") {
          getAudioPlayList(
              audioPlayerManager, studyPlanId!, dio, httpHead, minioHttp);
        }
      } catch (e) {
        print("Error: $e");
      }
    });
  }

  static void getAudioPlayList(AudioPlayerManager audioPlayerManager,
      String studyPlanId, Dio dio, String httpHead, String minioHttp) async {
    if (studyPlanId == "" || studyPlanId == null) {
      return;
    }
    final params = {"studyPlanId": studyPlanId, "status": 1 ,"playType": 1};
    final prefs = await SharedPreferences.getInstance();
    // 定义自定义头部信息
    final customHeaders = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ${prefs.getString(Constants.storageToken)}',
    };
    var aa;
    try {
      final response = await dio.post(
          httpHead + "/plStudyPlanVideo/getPlStudyPlanVideoList",
          options: Options(headers: customHeaders),
          data: params);
      aa = response.data;
    } on DioError catch (e) {
      prefs.setString("playFlag", "0");
      print("+++++++++++++++" + e.message + "有问题");
      return;
    }
    if (aa['code'] == "00000") {
      List<dynamic> audioList = aa['data'];
      List<String> urlList = [];
      if (!audioList.isEmpty) {
        for (int i = 0; i < audioList.length; i++) {
          var vo = audioList[i];
          String audio = minioHttp + "/" + vo["audioUrl"];
          urlList.add(audio);
        }

        final VolumeController _volumeController = VolumeController();
        _volumeController.setVolume(0.50);
        audioPlayerManager.setAudioUrls(urlList);
        audioPlayerManager.playShufftle();
        prefs.setString("playFlag", "1");
      }
    }
  }
}
